package com.century.sjt.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Spannable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.activity.Topic.HomepageActivity;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.EMChat.utils.EaseSmileUtils;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TopicCommentListAdapter extends BaseAdapter{
    private LayoutInflater mLayoutInflater;
    // 映射数据
    private List<Map<String, String>> mDataList;
    private RequestQueue mQueue;
    private Context context;
    private long mSumTime;

    public TopicCommentListAdapter(Context context, List<Map<String, String>> list, RequestQueue mQueue) {
        mLayoutInflater = LayoutInflater.from(context);
        mDataList = list;
        this.mQueue = mQueue;
        this.context = context;
    }

    // 获取数据量
    @Override
    public int getCount() {
        return mDataList.size();
    }

    // 获取对应ID项对应的Item
    @Override
    public Object getItem(int position) {
        return mDataList.get(position);
    }

    // 获取对应项ID
    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        // 文艺式 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        //获取纳秒时间 更加精确
//        long start = System.nanoTime();
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            //由于我们只需要将XML转化为View，并不涉及到具体的布局，所以第二个参数通常设置为null
            convertView = mLayoutInflater.inflate(R.layout.topic_comment_list_item, null);
//            holder.img = (NetworkImageView) convertView.findViewById(R.id.niv_topic_comment_list_item_image);
            holder.img = (RoundedImageView) convertView.findViewById(R.id.niv_topic_comment_list_item_image);
            holder.title = (TextView) convertView.findViewById(R.id.tv_topic_comment_list_item_nickName);
            holder.content = (TextView) convertView.findViewById(R.id.tv_topic_comment_list_item_content);
            holder.time = (TextView) convertView.findViewById(R.id.tv_topic_comment_list_item_time);
            holder.lldelete = (LinearLayout) convertView.findViewById(R.id.ll_delete);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //取出map对象
        final Map map = mDataList.get(position);
        //设置控件的数据
        holder.title.setText((String) map.get("nickName"));
        //表情识别
        Spannable span = EaseSmileUtils.getSmiledText(context, (String) map.get("content"));
        holder.content.setText(span);
        holder.time.setText((String) map.get("createDateTime"));
        String imgId = (String) map.get("image");
        final String userId = (String) map.get("userId");
        final String topicId = (String) map.get("topicId");

        String imgUrl= Constant.ImageHost_Small + imgId;
        Glide.with(context).load(imgUrl).into(holder.img);
        //详情头像点击
        holder.img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, HomepageActivity.class).putExtra("userId", userId);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                context.startActivity(intent);
            }
        });

        SharedPreferences mainSharedPreferences = context.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        final String myUserId = mainSharedPreferences.getString("userId", "");

        //判断是否是本人，如果是出现删除按钮
        if(userId.equals(myUserId)){
            holder.lldelete.setVisibility(View.VISIBLE);
        }else {
            holder.lldelete.setVisibility(View.GONE);
        }

        // 删除评论
        holder.lldelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle(context.getResources().getString(R.string.text_prompt));
                builder.setMessage(context.getResources().getString(R.string.error_is_delete));
                builder.setPositiveButton(context.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteTopic(topicId , myUserId , position);
                    }
                });
                builder.setNegativeButton(context.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                builder.create().show();
            }
        });

//        long end = System.nanoTime();
//        long dValue = end - start;
//        mSumTime += dValue;
        //输出每次getView消耗的时间和
        //Log.d("xys", String.valueOf(mSumTime));
        return convertView;
        // 文艺式 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>16325820
    }

    // ViewHolder用于缓存控件
    class ViewHolder{
//        public NetworkImageView img;
        public RoundedImageView img;
        public TextView title;
        public TextView content;
        public TextView time;
        public LinearLayout lldelete;
    }

    public void addItem(Map<String, String> map){
        mDataList.add(map);
    }
    public void deleteTopic(final String topicId, final String userId, final int position){
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,context. getResources().getString(R.string.error_please_waitting), context);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.DeleteComment, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("删除评论", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        mDataList.remove(position);
//                        reTopicCommentList(sysId);
                        TipUtil.showToast(context.getResources().getString(R.string.error_delete_success), context, 1);
                    } else {//失败
                        TipUtil.showToast(message, context, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(context.getResources().getString(R.string.error_service), context, 1);
                }
                TipUtil.closeProgressDialog();
                notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(context.getResources().getString(R.string.error_network),context, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =context. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("sysId",topicId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =context. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    private void reTopicCommentList(final String sysId) {

        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, Constant.TopicCommentListHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e("话题评论列表", s);
                try {
                    JSONTokener jsonTokener = new JSONTokener(s);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String code = res.getString("code");
                    String Message = res.getString("message");
                    if (code.equals("200")) {
                        JSONArray data = res.getJSONArray("data");
                        if (data.length() != Constant.PAGESIZE) {
                        }
                        for (int i = 0; i < data.length(); i++) {
                            //评论
                            JSONObject commentList = (JSONObject) data.get(i);
                            String commentId = commentList.getString("sysId");
                            String content = commentList.getString("content");
                            String createDateTime = commentList.getString("createDateTime");
                            //用户
                            JSONObject user = commentList.getJSONObject("user");
                            String userId = user.getString("sysId");
                            String nickName = user.getString("nickName");
                            String image = user.getString("image");


                            Map<String, String> map = new HashMap<>();
                            map.put("topicId",commentId);
                            map.put("userId", userId);
                            map.put("nickName", nickName);
                            map.put("image", image);
                            map.put("content", content);
                            map.put("createDateTime", createDateTime);
                            Log.e("image", image);
                            mDataList.add(map);

                        }

                        //Toast.makeText(MyTopicDetail.this, "200！", Toast.LENGTH_LONG).show();
                    } else {
//                        loadMore.setText("没有更多评论");
//                        loadMore.setEnabled(false);
//                        Toast.makeText(MyTopicDetail.this,Message,Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(context, context.getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
//                Message msg = new Message();
//                msg.what = 1;
//                mHandler.sendMessage(msg);
                notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                Toast.makeText(context, context.getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("topicId", sysId);
                map.put("paging.currentPage", "1");
                map.put("paging.pageSize", Constant.PAGESIZE + "");
                return map;
            }
        };
        mQueue.add(stringRequest1);


        //话题的评论列表（结束）
    }
}
